package com.xuanyuan.base.utils

import android.content.res.Resources
import android.os.Looper
import android.util.TypedValue
import androidx.lifecycle.MutableLiveData

/**
 * Describe:kotlin扩展属性及扩展方法相关,用于进行常规数据转换
 * Created by ken.luo on 2022/10/6
 */

/**
 * MutableLiveData扩展方法，根据当前线程自动选择update or set
 */
fun <T> MutableLiveData<T>.updateValue(value: T?, alwaysChange: Boolean = true) {
    if (!alwaysChange) {
        if (this.value == value) {
            return
        }
    }
    if (Thread.currentThread() != Looper.getMainLooper().thread) {
        this.postValue(value)
    } else {
        this.value = value
    }
}

/**
 * MutableLiveData扩展方法，List添加元素可供外界监听
 */
fun <T> MutableLiveData<MutableList<T>>.updateList(value: T) {
    var list = this.value
    if (list == null) {
        list = mutableListOf()
    }
    list.add(value)
    this.updateValue(list)
}

/**
 * Float将dp转为px
 */
val Float.dp: Float
    get() = TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP, this, Resources.getSystem().displayMetrics
    )

/**
 * Int将dp转为px
 */
val Int.dp: Float
    get() = this.toFloat().dp

/**
 * 将byteArray转为hex字符串
 */
fun ByteArray.toHexString(): String =
    joinToString(separator = "") { eachByte -> "%02x".format(eachByte) }
